package organ

import (
	"encoding/csv"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"

	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

func DownBrandList(c *gin.Context) {
	var data models.OrganBrand
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	if index := c.Request.FormValue("brandId"); index != "" {
		data.BrandId = tools.StrToInt(err, index)
	}

	data.BrandName = c.Request.FormValue("brandName")
	data.BrandRegister = c.Request.FormValue("brandRegister")
	data.BrandCompany = c.Request.FormValue("brandCompany")
	data.BrandQualify = c.Request.FormValue("brandQualify")
	data.BrandFinancing = c.Request.FormValue("brandFinancing")
	data.CreateBy = c.Request.FormValue("createBy")
	data.UpdateBy = c.Request.FormValue("updateBy")
	data.ApprovalStatus = c.Request.FormValue("approvalStatus")
	data.ApprovalAt = c.Request.FormValue("approvalAt")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")
	data.ApprovalUserId = c.Request.FormValue("approvalUserId")

	data.ApprovalUserName = c.Request.FormValue("approvalUserName")
	uid := tools.GetUserIdStr(c)
	if uid == "" {
		app.OK(c, nil, "请登陆后操作数据")
		return
	}
	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)

	header := []string{"品牌名称", "公司名称", "品牌成立时间", "办学资质", "财务授权", "融资情况", "优秀业绩", "课程数量",
		"平台订单量", "研发能力", "教学体系", "更新时间", "审核人"} //标题
	cellist := [][]string{
		header,
	}
	cellist = DataToStringV2(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetPage(pageSize, pageIndex)
		if len(result) <= 0 {
			break
		}
		cellist = DataToStringV2(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "BRAND_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)
}

// "品牌名称", "公司名称", "品牌成立时间", "办学资质", "财务授权",  "融资情况", "优秀业绩", "课程数量",
// 		"平台订单量", "研发能力", "教学体系", "更新时间","审核人"
func DataToStringV2(list []models.OrganBrand, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		context := []string{
			list[i].BrandName,
			list[i].BrandCompany,
			list[i].BrandRegister,
			list[i].BrandQualify,
			list[i].BrandFina,
			list[i].BrandFinancing,
			list[i].BrandExcellentBusiness,
			tools.IntToString(list[i].BrandCourseNums),
			tools.IntToString(list[i].BrandOrderNums),
			list[i].BrandDevelopPower,
			list[i].BrandTeacher,
			list[i].UpdatedAt.Format("2006-01-02 15:04:05"),
			list[i].UpdateBy,
		}
		data = append(data, context)
	}
	return data
}

func GetOrganBrandList(c *gin.Context) {
	var data models.OrganBrand
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	if index := c.Request.FormValue("brandId"); index != "" {
		data.BrandId = tools.StrToInt(err, index)
	}

	data.BrandName = c.Request.FormValue("brandName")
	data.BrandRegister = c.Request.FormValue("brandRegister")
	data.BrandCompany = c.Request.FormValue("brandCompany")
	data.BrandQualify = c.Request.FormValue("brandQualify")
	data.BrandFinancing = c.Request.FormValue("brandFinancing")
	data.CreateBy = c.Request.FormValue("createBy")
	data.UpdateBy = c.Request.FormValue("updateBy")
	data.ApprovalStatus = c.Request.FormValue("approvalStatus")
	data.ApprovalAt = c.Request.FormValue("approvalAt")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")
	data.ApprovalUserId = c.Request.FormValue("approvalUserId")
	data.ApprovalUserName = c.Request.FormValue("approvalUserName")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func GetOrganBrand(c *gin.Context) {
	var data models.OrganBrand
	data.BrandId, _ = tools.StringToInt(c.Param("id"))
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func InsertOrganBrand(c *gin.Context) {
	var data models.OrganBrand
	err := c.ShouldBindJSON(&data)

	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.UpdateBy = tools.GetUserIdStr(c)
	data.CreateBy = tools.GetUserIdStr(c)
	data.CreateByName = tools.GetUserName(c)
	data.UpdateByName = tools.GetUserName(c)
	var user models.SysUser
	uidInfo, _ := user.GetById(tools.GetUserId(c))
	if uidInfo.UserType == "3" {
		data.OrganId = uidInfo.OrganId
		data.OrganName = uidInfo.OrganName
	}
	result, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func UpdateOrganBrand(c *gin.Context) {
	var data models.OrganBrand
	err := c.ShouldBindJSON(&data)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	var user models.SysUser
	uidInfo, _ := user.GetById(tools.GetUserId(c))
	if uidInfo.UserType == "3" {
		data.OrganId = uidInfo.OrganId
		data.OrganName = uidInfo.OrganName
	}
	data.UpdateBy = tools.GetUserIdStr(c)
	data.CreateBy = tools.GetUserIdStr(c)
	data.CreateByName = tools.GetUserName(c)
	data.UpdateByName = tools.GetUserName(c)
	result, err := data.Update(data.BrandId)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func CheckOrganBrand(c *gin.Context) {
	var data models.OrganBrand
	var checkReq models.CheckReq
	err := c.BindWith(&checkReq, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.BrandId = checkReq.Id
	data.ApprovalStatus = checkReq.ApprovalStatus
	data.ApprovalUserId = tools.GetUserIdStr(c)
	data.ApprovalUserName = tools.GetUserName(c)
	data.ApprovalAt = time.Now().Format("2006-01-02 15:04:05")
	result, err := data.Update(data.BrandId)
	if err != nil {
		tools.HasError(err, "操作失败"+err.Error(), -1)
	}

	app.OK(c, result, "操作成功")
}

func DeleteOrganBrand(c *gin.Context) {
	var data models.OrganBrand

	IDS := tools.IdsStrToIdsIntGroup("id", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据删除失败："+err.Error(), nil)
		return
	}

	app.OK(c, nil, msg.DeletedSuccess)
}
